<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2021/8/19
 * Time: 1:29 下午
 */

namespace app\common\cachemodel\live;

use app\common\model\BaseCache;
use think\Cache;
use think\Log;
use XznsTools\cache\CacheManage;

/**
 * Class LiveAnchorInfo
 * @package app\common\cachemodel\live
 */
class LiveAnchorInfo extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_anchor_info';
    protected $cacheModel = 'live.live_anchor';

    public function updateData($liveId, $data)
    {
        try
        {
            $this->where('live_id', $liveId)->update($data);

            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $liveId)->rmCache();
        }
        catch (\Exception $e)
        {
            return false;
        }

        return true;
    }

    /**
     * 判断当前用户是否是直播
     * @param $uid
     * @return array|mixed
     * @throws \Exception
     */
    public function getUserAnchor($uid)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid)->ZsGetIocData('list', function () use ($uid)
        {
            try
            {
                $ids = $this->where(['uid' => $uid])->column('live_id', 'live_id');
                $ids = array_flip_key_value($ids);
            }
            catch (\Exception $e)
            {
                $ids = [];
            }
            return $ids;
        });
    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $data = $this->where(['live_id' => ['in', $ids]])->column('*', 'live_id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    /**
     * 获取榜单规则
     */
    public function getListRules()
    {
        return [
            'title' => '热度贡献榜奖励规则',
            'rules' => [
                '每日（以次日0点截止计算）星座点赞贡献热度前三名的用户可获得1个小准准，自动发放至礼物背包。',
                '每日（以次日0点截止计算）综合贡献热度最高的用户可获得1个准备暴富，自动发放至礼物背包。',
                '每日（以次日0点截止计算）星座热度排行榜第一名的星座用户可获得1个幸运星，自动发放至礼物背包。'
            ]
        ];
    }

    /**
     * 获取免费礼物规则
     */
    public function getGiftRules()
    {
        return [
            [
                'title' => '幸运星',
                'rules' => [
                    '连续在线观看10分钟，可获得1个幸运星，每日限1个；累计在线观看1小时当日直播，可获得2个幸运星（每日限2个）；获取后自动放置背包中。',
                    '每日（以次日0点截止计算）星座热度排行榜第一名的星座用户可获得1个幸运星，自动发放至礼物背包。',
                ]
            ],
            [
                'title' => '小准准',
                'rules' => [
                    '每周2天进入直播间，且每次连续在线观看时长不低于10分钟，可获得1个小准准；当月累计8天进入直播间，且每次连续观看时长不低于10分钟，可获得3个小准准；获取后自动发放至背包中。',
                    '每日（以次日0点截止计算）热度日榜前三名的星座用户可获得1个小准准，自动发放至礼物背包。',
                ]
            ],
            [
                'title' => '准备暴富',
                'rules' => [
                    '当日礼物贡献值超过500，可获得1个准备暴富；礼物贡献值累计超过10000，可获得2个准备暴富。',
                ]
            ],
        ];
    }

    /**
     * 获取主播扩展配置 指定 信息
     * @param int $liveId
     * @param string $configName
     * @return array|int[]|mixed
     * @throws \Exception
     */
    public function getAnchorExtendConfig(int $liveId, string $configName)
    {
        $AnchorConfig = $this->getInfoById($liveId, ['extend_config']);
        try
        {
            $extendConfig = !empty($AnchorConfig['extend_config']) ? json_decode($AnchorConfig['extend_config'], true) : [];
        }
        catch (\Exception $e)
        {
            Log::write("获取主播配置【{$configName}】信息异常：{$e->getMessage()}", 'error');
            $extendConfig = [];
        }

        if (isset($extendConfig[$configName]))
        {
            return $extendConfig[$configName];
        } else
        {
            // 没有配置 返回默认配置
            switch ($configName)
            {
                case 'rtc_config':
                    $config = [
                        'rtc_auth' => 1,
                        'rtc_max_user' => 50
                    ];
                    break;
                case 'astro_config':
                    $config = [
                        'is_free_choose_recode' => 1,
                        'is_allow_synastry' => 1,
                        'max_people_num' => 5,
                        'question_require' => '',
                        'people_auth' => 1
                    ];
                    break;
                case 'dice_config': // 骰子默认配置
                case 'tarot_config':    // 塔罗默认配置
                    $config = [
                        'max_people_num' => 10,
                        'question_require' => '',
                        'people_auth' => 1,
                    ];
                    break;
                default:
                    $config = [];
            }

            return $config;
        }
    }

    /**
     * 设置主播扩展配置 指定 信息
     * @param int $liveId
     * @param string $configName
     * @param $configData
     * @throws \Exception
     */
    public function setAnchorExtendConfig(int $liveId, string $configName, $configData)
    {
        $AnchorConfig = $this->getInfoById($liveId, ['extend_config']);
        $extendConfig = !empty($AnchorConfig['extend_config']) ? json_decode($AnchorConfig['extend_config'], true) : [];

        $extendConfig[$configName] = $configData;

        $extendConfigStr = json_encode($extendConfig, JSON_UNESCAPED_UNICODE);
        // 更新扩展配置信息
        $this->updateData($liveId, ['extend_config' => $extendConfigStr]);
    }

    /**
     * 获取连麦配置
     * @param int $liveId
     * @return array|int[]|mixed
     * @throws \Exception
     */
    public function getRtcConfig(int $liveId): array
    {
        // 获取最新的直播记录ID
        $liveRecordId = (new LiveRecordingInfo())->getNewestRecord($liveId);
        // 获取rtc配置信息
        $rtcConfig = $this->getAnchorExtendConfig($liveId, 'rtc_config');
        // 获取当前 rtc开关开启状态
        $rtcSwitch = (int)(Cache::get("live:rtc_switch:{$liveId}:{$liveRecordId}", 0));

        $rtcConfig['rtc_switch'] = $rtcSwitch;

        return $rtcConfig;
    }

    /**
     * 获取 解答 配置 信息
     * @param int $liveId
     * @param int $liveRecordId
     * @param string $configName astro=>看盘 dice=>骰子 tarot=>塔罗
     * @return array|int[]|mixed
     * @throws \Exception
     */
    public function getAnswerConfig(int $liveId, int $liveRecordId, string $configName)
    {
        // 获取rtc配置信息
        $resConfig = $this->getAnchorExtendConfig($liveId, $configName . '_config');
        // 获取当前 解答 付费信息
        $resPayInfo = $this->getAnswerPayInfo($liveId, $liveRecordId, [$configName]);
        // 获取当前 星盘解答开关开启状态
        $switchConfig = $this->getAnswerSwitchInfo($liveId, $liveRecordId, [$configName]);

        $resConfig['switch'] = $switchConfig[$configName];

        $resConfig['type'] = $resPayInfo[$configName]['type'];

        $resConfig['price'] = $resPayInfo[$configName]['price'];

        return $resConfig;
    }

    /**
     * 获取 解答开关配置信息
     * @param int $liveId
     * @param int $liveRecordId
     * @param array $names astro=>看盘 dice=>骰子 tarot=>塔罗
     * @return array
     * @throws \Exception
     */
    public function getAnswerSwitchInfo(int $liveId, int $liveRecordId, array $names = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('answer_switch', $liveId . ':' . $liveRecordId)
            ->getCache($names, 'answer_switch');

        if (count($names) === 1)
        {
            $resSwitch[$names[0]] = (int)$data;
        } else
        {
            $names = $names ?: ['astro', 'dice', 'tarot'];  // astro=>看盘 dice=>骰子 tarot=>塔罗

            $resSwitch = [];
            foreach ($names as $item)
            {
                $resSwitch[$item] = isset($data[$item]) && $data[$item] ? 1 : 0;
            }
        }

        return $resSwitch;
    }

    /**
     * 设置 解答开关配置信息
     * @param int $liveId
     * @param int $liveRecordId
     * @param string $name
     * @param int $switch 1=>开 0=>关
     * @throws \Exception
     */
    public function setAnswerSwitchInfo(int $liveId, int $liveRecordId, string $name, int $switch)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('answer_switch', $liveId . ':' . $liveRecordId)
            ->setCacheTime(86400) // 一天有效期
            ->setCache([$name => $switch], 'answer_switch', false);
    }

    /**
     * 获取 解答 付费信息
     * @param int $liveId
     * @param int $liveRecordId
     * @param array $names
     * @return array
     * @throws \Exception
     */
    public function getAnswerPayInfo(int $liveId, int $liveRecordId, array $names = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('answer_pay_info', $liveId . ':' . $liveRecordId)
            ->getCache($names, 'answer_pay_info');

        if (count($names) === 1)
        {
            $resInfo[$names[0]] = $data ? json_decode($data, true) : ['type' => 1, 'price' => 0];
        } else
        {
            $names = $names ?: ['astro', 'dice', 'tarot'];  // astro=>看盘 dice=>骰子 tarot=>塔罗

            $resInfo = [];
            foreach ($names as $item)
            {
                $resInfo[$item] = isset($data[$item]) && $data[$item] ? json_decode($data[$item]) : ['type' => 1, 'price' => 0];    // type 1免费  2付费
            }
        }

        return $resInfo;
    }

    /**
     * 设置 解答开关配置信息
     * @param int $liveId
     * @param int $liveRecordId
     * @param string $name
     * @param array $payInfo // type 1免费  2付费  price 付费金额
     * @throws \Exception
     */
    public function setAnswerPayInfo(int $liveId, int $liveRecordId, string $name, array $payInfo)
    {
        CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('answer_pay_info', $liveId . ':' . $liveRecordId)
            ->setCacheTime(86400) // 一天有效期
            ->setCache([$name => json_encode($payInfo)], 'answer_pay_info', false);
    }
}
